package com.simple.editor.vcs;

import com.simple.editor.action.EditorException;
import com.simple.editor.callback.DefaultUICallbackImpl;
import com.simple.editor.vcs.svn.SvnCmdClient;

import java.util.Collections;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created with IntelliJ IDEA. User: vsoroka Date: 11.06.13 Time: 11:13 To
 * change this template use File | Settings | File Templates.
 */
public class VcsClientRegistry {

    private final AtomicReference<VcsClient> currentVcsClient = new AtomicReference<VcsClient>();
    private final SvnCmdClient svnCmdClient;

    public VcsClientRegistry() {
        svnCmdClient = new SvnCmdClient();
    }

    public void setVcsClientForThePath(final VcsFile file) throws EditorException {
        final VcsClient client = checkForSvnCommandClient(file);
        if (client == null) {
            throw new EditorException("Unknown VCS. Note, currently supported only SVN used system command line utility");
        }
        this.currentVcsClient.set(client);
    }

    public VcsClient getCurrentVcsClient() {
        return currentVcsClient.get();
    }

    private VcsClient checkForSvnCommandClient(final VcsFile file) throws EditorException {
        VcsClient vcsClient = null;
        final MyUICallback callback = new MyUICallback();
        final Future<Void> future = svnCmdClient.refreshStatus(callback, Collections.singletonList(file));

        try {
            future.get();
        } catch (Exception ex) {
            throw new EditorException(ex.getMessage(), ex);
        }
        if (callback.getException() != null) {
            throw callback.getException();
        } else if (file.getStatus() != VcsStatus.UNKNOWN) {
            vcsClient = svnCmdClient;
        }
        return vcsClient;
    }

    private static class MyUICallback extends DefaultUICallbackImpl {
        private EditorException exception;

        @Override
        public void onFailure(final Exception ex) {
            exception = new EditorException(ex.getMessage(), ex);
        }

        private EditorException getException() {
            return exception;
        }
    }
}
